package icu.ac.kr.simpleRssReader.activity;

import java.io.FileNotFoundException;
import java.util.HashMap;

import icu.ac.kr.simpleRssReader.*;
import icu.ac.kr.simpleRssReader.network.DownloadManager;
import icu.ac.kr.simpleRssReader.provider.RssDBProviderConstant;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ChannelList extends Activity {

	static final String TAG = "ChannelList";
	
	static final int NORMALGROUP = 1;
	static final int SPECIALGROUP = 2;  // refresh and delete if there are channel registered
	
	static final int ADDCHANNEL = 1;
	static final int REFRESH = 2;
	static final int DELCHANNEL = 3;
	
	DownloadManager downloadManager;
	Handler handler;
	
	private class DelStructure{
		
		long id;
		String title;
	};
	
	HashMap <Integer, DelStructure> delChannel;
	
	Cursor cursor;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	
		setContentView(R.layout.channellist);
		cursor = getContentResolver().query(RssDBProviderConstant.CHANNEL_URI, new String[] {"_id", "title", "url"},null, null, null);
		ListView list = (ListView) findViewById(R.id.list);
		ChannelAdapter adapter = new ChannelAdapter(this, cursor);
		list.setAdapter(adapter);

		list.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long id) {
				// TODO Auto-generated method stub
				Log.d(TAG, "Selected Item : " + id);
				startActivity(new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(RssDBProviderConstant.CHANNEL_URI, id )));
			}
			
		});
	}
  
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		cursor.close();
		cursor = getContentResolver().query(RssDBProviderConstant.CHANNEL_URI, new String[] {"_id", "title", "url"},null, null, null);
		ListView list = (ListView) findViewById(R.id.list);
		ChannelAdapter adapter = new ChannelAdapter(this, cursor);
		list.setAdapter(adapter);
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		
		menu.clear();
		menu.add(NORMALGROUP, ADDCHANNEL, 0, "Add channel");
		if (cursor.getCount() > 0)
		{
			menu.add(NORMALGROUP, REFRESH, 0, "Refresh Channels");
			SubMenu sub = menu.addSubMenu("Delete Channel");
			int count = 0;	
			cursor.moveToFirst();
			do 
			{	
			sub.add(NORMALGROUP, DELCHANNEL + count  , 0, cursor.getString(cursor.getColumnIndex(RssDBProviderConstant.channel.TITLE)) ) ; //cursor.getString(cursor.getColumnIndex(RssDBProviderConstant.channel.TITLE)));
			count += 1;
			}while (cursor.moveToNext());
			
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);
	
		switch(item.getItemId())
		{
		case ADDCHANNEL:
			startActivity(new Intent(Intent.ACTION_VIEW, RssDBProviderConstant.CHANNEL_URI));
			break;
		case REFRESH:
			//startActivity(new Intent(Intent.ACTION_VIEW, RssDBProviderConstant.CHANNEL_URI));
			Log.d(TAG, "refresh DB");
	
			
			if (downloadManager == null)
			{
				handler = new Handler();
				downloadManager = new DownloadManager(ChannelList.this, getContentResolver(), handler);
			
			}
			
			Thread thread = new Thread(){
				
				public void run(){
					
					downloadManager.refresh();
				}
				
			};
			
			thread.start();
			
			break;
		default:
			int order = item.getItemId();
			
			DelStructure delStructure  = delChannel.get(order);
			if (delStructure != null)
			{
					Log.d(TAG, "Selected Title : " + delStructure.title);
					getContentResolver().delete(RssDBProviderConstant.CHANNEL_URI, "title='"+delStructure.title+"'", null);
					getContentResolver().delete(RssDBProviderConstant.POST_URI, "channel_id='"+delStructure.id+"'", null);
					onResume();
			}
			break;
		}
	
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onPrepareOptionsMenu(menu);

		menu.clear();
		menu.add(NORMALGROUP, ADDCHANNEL, 0, "Add channel");
		if (cursor.getCount() > 0)
		{
			menu.add(NORMALGROUP, REFRESH, 0, "Refresh Channels");
			SubMenu sub = menu.addSubMenu("Delete Channel");
			int count = 0;	
			cursor.moveToFirst();
			delChannel =new HashMap<Integer, DelStructure>(); 
				
			do 
			{	
				DelStructure delStructure = new DelStructure();
				delStructure.id = cursor.getLong(cursor.getColumnIndex(RssDBProviderConstant.channel._ID));
				delStructure.title = cursor.getString(cursor.getColumnIndex(RssDBProviderConstant.channel.TITLE));
				sub.add(NORMALGROUP, DELCHANNEL + count  , 0, delStructure.title  ) ; //cursor.getString(cursor.getColumnIndex(RssDBProviderConstant.channel.TITLE)));
				delChannel.put(new Integer(DELCHANNEL+count), delStructure );
				count += 1;
			}while (cursor.moveToNext());
			
		}
		return true;
	}

	
	
	private class ChannelAdapter extends CursorAdapter{

		public ChannelAdapter(Context context, Cursor c) {
			super(context, c);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			// TODO Auto-generated method stub
	
			TextView chID = (TextView) view.findViewById(R.id.chID);
			TextView title = (TextView) view.findViewById(R.id.title);
			TextView url = (TextView) view.findViewById(R.id.url);
			chID.setText("Channel ID : "+cursor.getLong(cursor.getColumnIndex(RssDBProviderConstant.channel._ID)));
			title.setText(cursor.getString(cursor.getColumnIndex(RssDBProviderConstant.channel.TITLE)));
			url.setText(cursor.getString(cursor.getColumnIndex(RssDBProviderConstant.channel.URL)));
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			LayoutInflater inflater = LayoutInflater.from(context);
			View view = inflater.inflate(R.layout.channelrow, null);
			
			return view;
		}
		
		
	}
	
	
	
}
